package com.demo.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.demo.easyexcel.User;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
public class TestEasyExcel {
  @Data
  @ColumnWidth(20)
  public static class TestVO {
    @ExcelProperty(value = "*姓名", index = 0)
    private String name;
    @ExcelProperty(value = "*年龄", index = 1)
    private int age;
    @ExcelProperty(value = "学校", index = 2)
    private String school;
  }

  /**
   * 测试导出模板
   * 1. 标题指定某列标红色字段
   * 2. 标题指定某列加批注
   */
  //  @Test
  //  public void testExport1() throws FileNotFoundException {
  //    // 输出流
  //    OutputStream outputStream = new FileOutputStream(new File("D:\\1.xlsx"));
  //    // 导出的数据
  //    List<TestVO> dataList = new ArrayList<>();
  //    // 指定标红色的列
  //    List<Integer> columns = Arrays.asList(0, 1);
  //    // 指定批注
  //    HashMap<Integer,String> annotationsMap = new HashMap<>();
  //    annotationsMap.put(0, "第一列标题批注");
  //    annotationsMap.put(1, "第二列标题批注");
  //    TitleHandler titleHandler = new TitleHandler(columns, IndexedColors.RED.index, annotationsMap);
  //    EasyExcelUtil.writeExcelWithModel(outputStream, dataList, TestVO.class, "sheetName", titleHandler);
  //  }
  @GetMapping("export-test1")
  public void exportTest1(HttpServletResponse response) {
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setCharacterEncoding("utf-8");
    // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
    String fileName = null;
    try {
      fileName = URLEncoder.encode("测试easyexcel", "UTF-8").replaceAll("\\+", "%20");
    } catch (UnsupportedEncodingException e) {
      log.error("导出", e);
    }
    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    try {
      EasyExcelFactory.write(response.getOutputStream(), User.class).sheet("风险号码拦截统计数据明细").doWrite(createDataList());
    } catch (IOException e) {
      log.error("导出", e);
    }
  }

  private List<User> createDataList() {
    List<User> userList = new ArrayList<>();
    for (int i = 1; i <= 100; i++) {
      User user = new User();
      user.setUsername("test" + i);
      user.setAge(i);
      user.setNumber(BigInteger.valueOf(i));
      user.setDate(new Date());
      userList.add(user);
    }
    return userList;
  }

}